package com.jddup.program.dao.handler.impl;

import com.jddup.common.exception.JddupException;
import com.jddup.common.pojo.TableMeta;
import com.jddup.program.dao.handler.IDeleteHandler;
import com.jddup.program.dao.sqlbuilder.DeletePrepareSQLBuilder;
import com.jddup.program.etm.EntityToTableMetaConvertor;
import com.jddup.program.utils.POJOUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * PostgreSQL 删除方法
 * Created by ZZB on 2017/9/25.
 */
public class DeleteHandlerImpl implements IDeleteHandler {
	private DeletePrepareSQLBuilder deletePrepareSQLBuilder;
	private EntityToTableMetaConvertor entityToTableMetaConvertor;

	public DeleteHandlerImpl(DeletePrepareSQLBuilder deletePrepareSQLBuilder, EntityToTableMetaConvertor entityToTableMetaConvertor) {
		this.deletePrepareSQLBuilder = deletePrepareSQLBuilder;
		this.entityToTableMetaConvertor = entityToTableMetaConvertor;
	}

	@Override
	public <T> int deleteByPk(Object pk, Class<T> tClass, Connection connection) throws JddupException {
		TableMeta tableMeta = entityToTableMetaConvertor.convertFromClass(tClass);
		String sql = deletePrepareSQLBuilder.buildDeleteSQL(tableMeta);
		try {
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setObject(1, pk);
			return preparedStatement.executeUpdate();
		} catch (SQLException e) {
			throw new JddupException(e);
		}
	}

	@Override
	public <T> int[] deleteInPk(List<Object> pk, Class<T> tClass, Connection connection) throws JddupException {
		TableMeta tableMeta = entityToTableMetaConvertor.convertFromClass(tClass);
		String sql = deletePrepareSQLBuilder.buildDeleteSQL(tableMeta);
		try {
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			for (Object o : pk) {
				preparedStatement.setObject(1, o);
				preparedStatement.addBatch();
			}
			return preparedStatement.executeBatch();
		} catch (SQLException e) {
			throw new JddupException(e);
		}
	}

	@Override
	public int delete(Object o, Connection connection) throws JddupException {
		TableMeta tableMeta = entityToTableMetaConvertor.convertFromClass(o.getClass());
		String sql = deletePrepareSQLBuilder.buildDeleteSQL(tableMeta);
		try {
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			Object pk = POJOUtils.readDeclaredFieldByGetMethod(o, tableMeta.getPrimaryKeyColumn().getPropertyName());
			preparedStatement.setObject(1, pk);
			return preparedStatement.executeUpdate();
		} catch (SQLException | NoSuchFieldException | NoSuchMethodException | IllegalAccessException
				| InvocationTargetException e) {
			throw new JddupException(e);
		}
	}
}
